package com.chukun.reactor.single;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author chukun@meituan.com
 * @version 1.0.0
 * @description 分发器
 * @create 2022/1/24 20:05
 **/
public class DispatchHandler implements Runnable {

    private SocketChannel socketChannel;

    public DispatchHandler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        //打印当前线程名称，证明I/O是同一个线程来处理。
        System.out.println(Thread.currentThread().getName()+"---handler");
        ByteBuffer buffer=ByteBuffer.allocate(20);
        int len=0,total=0;
        String msg="";
        try {
            do {
                len = socketChannel.read(buffer);
                if (len > 0) {
                    total += len;
                    msg += new String(buffer.array());
                }
                buffer.clear();
            } while (len > buffer.capacity());
            System.out.println(socketChannel.getRemoteAddress()+":Server Receive msg:"+msg);

        }catch (Exception e){
            if(socketChannel!=null){
                try {
                    socketChannel.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }
}
